package cn.wenhe9.yygh.hosp.service.impl;

import cn.wenhe9.yygh.common.exception.YyghException;
import cn.wenhe9.yygh.common.result.ResultCodeEnum;
import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.hosp.repository.ScheduleRepository;
import cn.wenhe9.yygh.hosp.service.DepartmentService;
import cn.wenhe9.yygh.hosp.service.HospitalService;
import cn.wenhe9.yygh.hosp.service.ScheduleService;
import cn.wenhe9.yygh.model.hosp.BookingRule;
import cn.wenhe9.yygh.model.hosp.Department;
import cn.wenhe9.yygh.model.hosp.Hospital;
import cn.wenhe9.yygh.model.hosp.Schedule;
import cn.wenhe9.yygh.model.vo.hosp.BookingScheduleRuleVo;
import cn.wenhe9.yygh.model.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.format.DateTimeFormat;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author DuJinliang
 * 2022/3/28
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Resource
    private ScheduleRepository scheduleRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private HospitalService hospitalService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public ResultResponse save(Map<String, Object> paramMap) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(paramMap);
        Schedule schedule = objectMapper.readValue(json, Schedule.class);

        Optional<Schedule> scheduleOptional = scheduleRepository.findScheduleByHoscodeAndHosScheduleIdAndIsDeletedEquals(schedule.getHoscode(), schedule.getHosScheduleId(), 0);

        if (scheduleOptional.isPresent()){
            Schedule scheduleExist = scheduleOptional.get();

            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        }else {
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            schedule.setUpdateTime(new Date());
            schedule.setCreateTime(new Date());

            scheduleRepository.save(schedule);
        }

        return ResultResponse.ok();
    }

    @Override
    public ResultResponse findScheduleByPage(String hoscode, int page, int limit) {
        Pageable pageable = PageRequest.of(page, limit);

        Page<Schedule> schedulePage = scheduleRepository.findSchedulesByHoscodeAndIsDeletedEquals(hoscode, pageable, 0);

        return ResultResponse.ok(schedulePage);
    }

    @Override
    public ResultResponse logicDelete(String hoscode, String hosScheduleId) {
        Optional<Schedule> scheduleOptional = scheduleRepository.findScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (scheduleOptional.isPresent()){
            Schedule schedule = scheduleOptional.get();
            schedule.setIsDeleted(1);
            schedule.setUpdateTime(new Date());

            scheduleRepository.save(schedule);
        }
        return ResultResponse.ok();
    }

    @Override
    public ResultResponse findDepScheduleByPage(long page, long limit, String hoscode, String depcode) {
        //1.根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2.根据工作日期workDate进行分组
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("workDate")
                    .first("workDate").as("workDate")
                    .count().as("docCount")
                    //3.统计好源的数量
                    .sum("reservedNumber").as("reservedNumber")
                    .sum("availableNumber").as("availableNumber"),
            Aggregation.sort(Sort.Direction.DESC, "workDate"),
            //4.实现分页
            Aggregation.skip((page-1)*limit),
            Aggregation.limit(limit)
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> aggResults = aggregationResults.getMappedResults();

        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应的星期获取
        aggResults.stream().forEach(item -> item.setDayOfWeek(getDayOfWeek(new DateTime(item.getWorkDate()))));

        //设置最终的数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", aggResults);
        result.put("total", total);

        //获取医院名称
        String hosname = hospitalService.getHospname(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosname);
        result.put("baseMap", baseMap);

        return ResultResponse.ok(result);
    }

    @Override
    public ResultResponse getDetailSchedule(String hoscode, String depcode, String workDate) {

        List<Schedule> scheduleList = scheduleRepository.findSchedulesByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());

        //把得到的集合遍历，向其中设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.forEach(item -> {
            this.packageSchedule(item);
        });

        return ResultResponse.ok(scheduleList);
    }

    @Override
    public ResultResponse getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        //根据医院编号获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        BookingRule bookingRule = hospital.getBookingRule();
        //获取可预约日期的数据（分页）
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);
        //当前可预约的日期
        List<Date> dateList = iPage.getRecords();

        //获取可预约日期里科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                .count().as("docCount")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregateResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregateResult.getMappedResults();

        //合并数据 map集合 key日期 value 预约规则和剩余数量信息等
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)){
            scheduleVoMap = scheduleVoList.stream()
                    .collect(
                        Collectors.toMap(BookingScheduleRuleVo::getWorkDate, bookingScheduleRuleVo -> bookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            Date date = dateList.get(i);
            //从map集合根据key日期获取value值
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //如果当天没有排班医生
            if (bookingScheduleRuleVo == null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数 -1 表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前可预约的日期对应的星期
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约 状态 0 正常 1 即将放号 -1 当天已停止挂号
            if (i == dateList.size()-1 && page == iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间，不能预约
            if (i == 0 && page == 1){
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()){
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());

        //其他基础数据
        Map<String ,String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospname(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());

        result.put("baseMap", baseMap);

        return ResultResponse.ok(result);
    }

    @Override
    public Schedule getScheduleById(String scheduleId) {
        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
        if (scheduleOptional.isPresent()){
            Schedule schedule = scheduleOptional.get();
            this.packageSchedule(schedule);
            return schedule;
        }
        return null;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班信息
        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
        if (!scheduleOptional.isPresent()){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Schedule schedule = scheduleOptional.get();
        //获取预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital == null){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //把获取到的数据设置到scheduleOrderVo中
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospname(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepname(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 获取可预约日志分页数据
     * @param page Integer
     * @param limit Integer
     * @param bookingRule BookingRule
     * @return IPage
     */
    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //获取当天放号时间 年 月 日 小时 分钟
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当天放号时间已经过去，预约周期从后一天开始计算，周期加1
        if (releaseTime.isBeforeNow()){
            cycle+=1;
        }
        //获取可预约所有日志，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime currentDateTime = new DateTime().plusDays(i);
            String dateString = currentDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //因为预约周期不同，每页显示的日期最多七天数据，超过七天分页
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page -1) * limit + limit;
        //如果可以显示的数据小于limit，直接显示
        if (end > dateList.size()){
            end = dateList.size();
        }

        for (int i = start; i < end; i++){
            pageDateList.add(dateList.get(i));
        }
        //如果可以显示的数据大于limit，进行分页
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, limit, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将date日期（yyyy-MM-dd） 转换成DateTime
     * @param date Date
     * @param timeString String
     * @return DateTime
     */
    private DateTime getDateTime(Date date, String timeString){
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    private void packageSchedule(Schedule schedule){
        //设置医院名称
        schedule.getParam().put("hosname", hospitalService.getHospname(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname", departmentService.getDepname(schedule.getHoscode(), schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    private String getDayOfWeek(DateTime dateTime){
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()){
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
                break;
        }

        return dayOfWeek;
    }


}
